'use strict';

const { DataTypes } = require('sequelize');
const sequelize = require('../../database/sequelize');
const TravelPlan = require('./travel_plan');

const DailyPlan = sequelize.define(
  'DailyPlan',
  {
    id: {
      type: DataTypes.INTEGER.UNSIGNED,
      primaryKey: true,
      autoIncrement: true,
      comment: '每日计划ID',
    },
    plan_id: {
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: false,
      comment: '所属旅行计划ID',
    },
    day: {
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: false,
      comment: '第几天，从1开始',
    },
    date: {
      type: DataTypes.DATEONLY,
      allowNull: true,
      comment: '当天日期',
    },
    city_name: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: '当天主要城市名称（可选）',
    },
    note: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: '当日备注',
    },
  },
  {
    tableName: 'daily_plans',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    underscored: true,
  }
);

// 关联：每日计划 属于 旅行计划；旅行计划 拥有 多个每日计划
DailyPlan.belongsTo(TravelPlan, { foreignKey: 'plan_id', as: 'plan', onDelete: 'CASCADE' });
TravelPlan.hasMany(DailyPlan, { foreignKey: 'plan_id', as: 'dailyPlans', onDelete: 'CASCADE' });

// 初始化表与开发环境种子数据
(async () => {
  try {
    // await DailyPlan.sync({ alter: true });

    // 仅在开发环境且当前表无数据时插入示例每日计划
    if (process.env.NODE_ENV !== 'production') {
      const count = await DailyPlan.count();
      if (count === 0) {
        const plan = await TravelPlan.findOne({ order: [['id', 'ASC']] });
        if (plan) {
          const formatDate = (base, offset = 0) => {
            if (!base) return null;
            const d = new Date(base);
            d.setDate(d.getDate() + offset);
            const y = d.getFullYear();
            const m = String(d.getMonth() + 1).padStart(2, '0');
            const da = String(d.getDate()).padStart(2, '0');
            return `${y}-${m}-${da}`;
          };

          await DailyPlan.bulkCreate([
            { plan_id: plan.id, day: 1, date: formatDate(plan.start_date, 0), city_name: null, note: '抵达日，轻松行程' },
            { plan_id: plan.id, day: 2, date: formatDate(plan.start_date, 1), city_name: null, note: '浅草寺与天空树' },
          ]);
          console.log('✅ 已插入示例每日计划数据');
        }
      }
    }
  } catch (e) {
    console.error('DailyPlan 模型初始化失败:', e);
  }
})();

module.exports = DailyPlan;